<?php


namespace app\home\controller;

use app\home\model\Browse;
use app\home\model\NewsLetter;
use app\home\model\WechatUser;

/**
 * Class News
 * @package app\home\controller
 * 公司简讯letter
 */
class News extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->anonymous();
        $this->jssdk();
    }

    /**
     *  公司新闻首页
     */
    public function index () {
        $length = input('length',0);
        $letterModel = new NewsLetter();
        $map = ['status' => 1];
        $list = $letterModel->where($map)->limit($length,8)->order('id desc')->select();
        int_to_string($list,['type' => [1 => "新闻" , 2 => "通知"]]);
        if(IS_POST) {
            if($list) {
                return $this->success("加载成功","",$list);
            }else {
                return $this->error("加载失败");
            }
        }else {
            $this->assign('list',json_encode($list));
            return $this->fetch();
        }
    }

    /**
     *  公司新闻详情
     */
    public function detail () {
        $id = input('id');
        $userId = session('userId');
        $Model = new NewsLetter();
        if($userId != "visitor") {
            //判断流量量增加
            $map_browser = [
                'uid' => $userId,
                'aid' => $id,
                'type' => 2
            ];
            $res = Browse::where($map_browser)->find();
            if(!$res) {
                $Model->where('id',$id)->setInc('views');
            }
            $this->browser(2,$userId,$id);
        }
        $detail = $Model->get($id);
        $map = [
            'type' => 2, //公司简讯浏览
            'aid' => $id,
        ];
        $browser = Browse::where($map)->field('id,aid,uid,create_time')->order('create_time asc')->select();
        foreach ($browser as $key => $value) {
            $user = WechatUser::where(['userid' => $value['uid']])->find();
            $value['username'] = $user['name'];
            $value['header'] = $user['header'] ? $user['header'] : $user['avatar'];
        }
        $detail['browser_user'] = $browser;
        $this->assign('detail',json_encode($detail));
        $this->assign('userid',$userId);

        return $this->fetch();
    }
}
